package com.salt.service.impl;

import com.salt.service.VerificationCodeService;
import com.salt.util.SmsUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private final SmsUtil smsUtil;
    private final StringRedisTemplate redisTemplate;
    
    private static final String CODE_PREFIX = "verification_code:";
    private static final int CODE_LENGTH = 6;
    private static final int CODE_EXPIRE_MINUTES = 5;
    
    @Override
    public boolean sendCode(String mobile) {
        // 生成6位随机验证码
        String code = generateCode();
        
        // 发送验证码
        boolean success = smsUtil.sendVerificationCode(mobile, code);
        if (success) {
            // 将验证码保存到Redis，设置5分钟过期
            redisTemplate.opsForValue().set(
                CODE_PREFIX + mobile,
                code,
                CODE_EXPIRE_MINUTES,
                TimeUnit.MINUTES
            );
            log.info("验证码发送成功: {}", mobile);
            return true;
        }
        return false;
    }
    
    @Override
    public boolean verifyCode(String mobile, String code) {
        // 从Redis获取验证码
        String savedCode = redisTemplate.opsForValue().get(CODE_PREFIX + mobile);
        if (savedCode == null) {
            log.warn("验证码已过期: {}", mobile);
            return false;
        }
        
        // 验证码比对
        boolean success = savedCode.equals(code);
        if (success) {
            // 验证成功后删除验证码
            redisTemplate.delete(CODE_PREFIX + mobile);
            log.info("验证码验证成功: {}", mobile);
        } else {
            log.warn("验证码验证失败: {}", mobile);
        }
        return success;
    }
    
    /**
     * 生成随机验证码
     */
    private String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
} 